<script setup>
import { ref, onMounted, computed } from 'vue'
import { useUserInfoStore } from '@/stores/userInfo'
import {ElMessage, ElMessageBox} from 'element-plus'
import { getUserOrders, applyRefund  } from '@/api/user'
import router from "@/router"
import { ArrowLeft } from '@element-plus/icons-vue'
import { cancelOrder, confirmReceive, updateUserLevelAndBenefits, getUserLevelByConsumption  } from '@/api/user'

const userInfoStore = useUserInfoStore()

const form = ref({
  id: null,
  username: '',
  mobile: '',
  email: '',
  gender: 0,
  birthday: '',
  avatar: '',
  levelId: null,
  discountRate: 1.0,
  pointsMultiplier: 1.0,
  points: 0,
  balance: 0.0,
  totalConsumption: 0.0,
})
const orderList = ref([])

// 定义排序优先级：数值越小，优先级越高
const statusPriority = {
  4: 0, // 退款审核中
  2: 1, // 待收货
  1: 2, // 待发货
  3: 3, // 已完成
  0: 4, // 已取消
  5: 5, // 已退款
  6: 6  // 退款被拒绝
}

// 修改排序逻辑
const sortedOrderList = computed(() => {
  return [...orderList.value].sort((a, b) => {
    const pA = statusPriority[a.status] ?? 99
    const pB = statusPriority[b.status] ?? 99
    if (pA !== pB) return pA - pB
    return new Date(b.createTime) - new Date(a.createTime)
  })
})


// 根据订单状态获取卡片样式
const getCardStyle = (status) => {
  switch (status) {
    case 1: // 待发货
      return {
        borderLeft: '4px solid #e6a23c',
        background: 'rgba(230, 162, 60, 0.05)'
      }
    case 2: // 待收货
      return {
        borderLeft: '4px solid #409eff',
        background: 'rgba(64, 158, 255, 0.05)'
      }
    case 3: // 已完成
      return {
        borderLeft: '4px solid #67c23a',
        background: 'rgba(103, 194, 58, 0.05)'
      }
    case 4: // 退款审核中
      return {
        borderLeft: '4px solid #ff9900',
        background: 'rgba(255, 153, 0, 0.05)'
      }
    case 5: // 已退款
      return {
        borderLeft: '4px solid #909399',
        background: 'rgba(144, 147, 153, 0.05)'
      }
    case 6: // 被拒绝
      return {
        borderLeft: '4px solid #f56c6c',
        background: 'rgba(245, 108, 108, 0.05)'
      }
    default:
      return {
        borderLeft: '4px solid #dcdfe6',
        background: '#f5f7fa'
      }
  }
}

// 格式化下单时间
const formatTime = (val) => {
  return new Date(val).toLocaleString()
}

// 格式化订单状态
const formatOrderStatus = (status) => {
  switch (status) {
    case 0:
      return '已取消'
    case 1:
      return '待发货'
    case 2:
      return '待收货'
    case 3:
      return '已完成'
    case 4:
      return '退款审核中'
    case 5:
      return '已退款'
    case 6:
      return '退款被拒绝'
    default:
      return '未知状态'
  }
}

// 小计格式化函数
const subtotalFormatter = (row) => {
  return (row.price * row.quantity).toFixed(2)
}

// 获取订单数据
const fetchOrders = async () => {
  const userId = userInfoStore.userInfo?.id
  if (!userId) {
    ElMessage.warning('请先登录')
    return router.push('/login')
  }

  try {
    const res = await getUserOrders(userId)
    if (res.status === true && res.data) {
      orderList.value = res.data
    } else {
      ElMessage.error('获取订单失败')
    }
  } catch (e) {
    ElMessage.error('网络异常')
  }
}

// 回到主会场
const backShopping = () => {
  router.push('/shopping')
}

onMounted(fetchOrders)

onMounted(() => {
  const u = userInfoStore.userInfo
  if (!u) return
  Object.assign(form.value, {
    id: u.id,
    username: u.username,
    mobile: u.mobile,
    email: u.email,
    gender: u.gender,
    birthday: u.birthday,
    avatar: u.avatar,
    levelId: u.levelId,
    discountRate: u.discountRate,
    pointsMultiplier: u.pointsMultiplier,
    points: u.points,
    balance: u.balance,
    totalConsumption: u.totalConsumption
  })
})

onMounted(() => {
  userInfoStore.fetchUserInfo()
})

const handleCancelOrder = async (orderId) => {
  try {
    await ElMessageBox.confirm('确定要取消该订单吗？', '提示', {
      type: 'warning'
    })

    const oldLevelId = userInfoStore.userInfo.levelId

    const res = await cancelOrder(orderId)
    if (res.data === true) {
      ElMessage.success('订单已取消')
      await fetchOrders?.()

      // ✅ 重新拉取用户信息，确保 totalConsumption 和 levelId 是最新
      await userInfoStore.fetchUserInfo()
      const newTotal = userInfoStore.userInfo.totalConsumption
      const newLevelInfo = getUserLevelByConsumption(newTotal)
      const newLevelId = newLevelInfo.levelId

      // ✅ 触发后端等级更新（不带 totalConsumption）
      await updateUserLevelAndBenefits({
        userId: userInfoStore.userInfo.id,
        ...newLevelInfo
      })

      // 可选：再拉一次用户信息，确保等级更新成功
      await userInfoStore.fetchUserInfo()

      if (newLevelId < oldLevelId) {
        ElMessageBox.alert(
            `您的等级已降为 ${newLevelId}，当前享受 ${(newLevelInfo.discountRate * 100).toFixed(0)}% 折扣，${newLevelInfo.pointsMultiplier} 倍积分返还。`,
            '等级变动提醒',
            { type: 'warning' }
        )
      }
    } else {
      ElMessage.error(res.message || '取消失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败: ' + (error.message || '未知错误'))
    }
  }
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case 1:
      return 'warning' // 待发货
    case 2:
      return 'primary' // 待收货
    case 3:
      return 'success' // 已完成
    case 4:
      return 'warning' // 退款审核中
    case 5:
      return 'info'    // 已退款
    case 6:
      return 'danger'  // 被拒绝
    case 0:
      return 'info'
    default:
      return 'info'
  }
}

const handleConfirmReceive = async (orderId) => {
  try {
    await ElMessageBox.confirm('确认已收到货物？', '提示', { type: 'warning' })
    const res = await confirmReceive(orderId)
    if (res.data === true) {
      ElMessage.success('确认收货成功')
      fetchOrders?.()
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败: ' + (error.message || '未知错误'))
    }
  }
}

const handleRefund = async (order) => {
  const user = userInfoStore.userInfo
  const level = user.levelId
  const amount = order.paymentAmount
  const orderId = order.id
  const oldLevelId = level

  let message = ''

  if (level === 5) {
    message = '尊贵的会员，本单已为您直接退单，为您带来的不便我们深感抱歉'
  } else if (level === 4) {
    if (amount < 1000) {
      message = '亲爱的会员，本单我们为您急速退单'
    } else {
      message = '已提交申请，请等待管理员处理'
    }
  } else {
    message = '已提交申请，请等待管理员处理'
  }

  try {
    const confirmed = await ElMessageBox.confirm(
        '您确认要申请退款吗？',
        '提示',
        { type: 'warning' }
    )

    const res = await applyRefund(orderId)
    if (res.data === true) {
      ElMessage.success(message)

      // 订单状态已变，重新获取订单列表
      await fetchOrders?.()

      // 若退款处理已变更消费记录（直接退款情况），重新拉用户信息判断是否降级
      await userInfoStore.fetchUserInfo()
      const newTotal = userInfoStore.userInfo.totalConsumption
      const newLevelInfo = getUserLevelByConsumption(newTotal)
      const newLevelId = newLevelInfo.levelId

      if (newLevelId < oldLevelId) {
        await updateUserLevelAndBenefits({
          userId: userInfoStore.userInfo.id,
          ...newLevelInfo
        })

        await userInfoStore.fetchUserInfo()

        let message = `您的等级已降为 ${newLevelId}，当前享受 ${(newLevelInfo.discountRate * 100).toFixed(0)}% 折扣，${newLevelInfo.pointsMultiplier} 倍积分返还。`;

        // 根据旧等级提示失去的特权
        if (oldLevelId === 5) {
          message += "\n\n您已失去：无条件退款特权！";
        } else if (oldLevelId === 4 && newLevelId < 4) {
          message += "\n\n您已失去：1000元以下商品急速退款特权！";
        }

        ElMessageBox.alert(
            message,
            '等级变动提醒',
            { type: 'warning' }
        )
      }
    } else {
      ElMessage.error(res.message || '申请退款失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败: ' + (error.message || '未知错误'))
    }
  }
}

const activeStatus = ref(null)  // null 表示“全部订单”

const filteredOrderList = computed(() => {
  if (activeStatus.value === null) {
    return sortedOrderList.value
  }
  return sortedOrderList.value.filter(order => order.status === activeStatus.value)
})

</script>

<template>
  <div class="order-container">
    <div class="header">
      <el-button type="primary" plain @click="backShopping">
        <el-icon><ArrowLeft /></el-icon>
        返回主会场
      </el-button>
      <h1 class="title">我的订单</h1>
    </div>

    <el-button-group class="order-filter-bar" style="margin-bottom: 20px">
      <el-button
          :type="activeStatus === null ? 'primary' : 'default'"
          @click="activeStatus = null"
      >全部</el-button>

      <el-button
          :type="activeStatus === 4 ? 'primary' : 'default'"
          @click="activeStatus = 4"
      >退款审核中</el-button>

      <el-button
          :type="activeStatus === 2 ? 'primary' : 'default'"
          @click="activeStatus = 2"
      >待收货</el-button>

      <el-button
          :type="activeStatus === 1 ? 'primary' : 'default'"
          @click="activeStatus = 1"
      >待发货</el-button>

      <el-button
          :type="activeStatus === 3 ? 'primary' : 'default'"
          @click="activeStatus = 3"
      >已完成</el-button>

      <el-button
          :type="activeStatus === 0 ? 'primary' : 'default'"
          @click="activeStatus = 0"
      >已取消</el-button>

      <el-button
          :type="activeStatus === 5 ? 'primary' : 'default'"
          @click="activeStatus = 5"
      >已退款</el-button>

      <el-button
          :type="activeStatus === 6 ? 'primary' : 'default'"
          @click="activeStatus = 6"
      >退款被拒</el-button>
    </el-button-group>


    <el-card class="order-main-card">
      <el-empty v-if="orderList.length === 0" description="暂无订单记录" />

      <div v-else class="order-list">
        <el-card
            v-for="order in filteredOrderList"
            :key="order.id"
            class="order-card"
            shadow="hover"
            :style="getCardStyle(order.status)"
        >
          <div class="order-header">
            <span class="order-no">订单号：{{ order.orderNo }}</span>
            <span class="order-time">下单时间：{{ formatTime(order.createTime) }}</span>
          </div>

          <el-table :data="order.items" border stripe size="small">
            <el-table-column label="商品">
              <template #default="{ row }">
                <div class="product-cell">
                  <el-image
                      :src="row.productImage"
                      class="product-image"
                      fit="cover"
                  />
                  <span class="product-name">{{ row.productName }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量"  align="center" />
            <el-table-column label="单价（元）"  align="right">
              <template #default="{ row }">
                {{ row.price.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="小计" align="right" :formatter="subtotalFormatter" />
          </el-table>

          <div class="order-info-section">
            <div class="order-address">
              <strong>收件人：</strong>
              {{ form.username }}
            </div>
            <div class="order-address">
              <strong>手机号：</strong>
              {{ form.mobile }}
            </div>

            <div class="order-address">
              <strong>收货地址：</strong>
              {{ order.deliveryAddress?.province }}{{ order.deliveryAddress?.city }}{{ order.deliveryAddress?.district }}{{ order.deliveryAddress?.detail }}
            </div>
          </div>

          <div class="order-actions">
            <el-tag :type="getStatusTagType(order.status)" size="large">
              {{ formatOrderStatus(order.status) }}
            </el-tag>

            <el-button
                v-if="[1].includes(order.status)"
                type="danger"
                size="small"
                @click="handleCancelOrder(order.id)"
            >
              取消订单
            </el-button>
            <el-button
                v-if="[2, 3].includes(order.status)"
                type="warning"
                size="small"
                @click="handleRefund(order)"
            >
              申请退款
            </el-button>
            <el-button
                v-if="order.status === 2"
                type="success"
                size="small"
                @click="handleConfirmReceive(order.id)"
            >
              确认收货
            </el-button>
          </div>

          <div class="order-footer">
            <span class="order-total">
              实付金额：<span class="total-amount">￥{{ order.paymentAmount.toFixed(2) }}</span>
            </span>
          </div>
        </el-card>
      </div>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.order-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;

  .header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;

    .title {
      margin-left: 20px;
      font-size: 24px;
      color: #333;
    }
  }

  .order-main-card {
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    :deep(.el-card__body) {
      padding: 20px;
    }
  }

  .order-list {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }

  .order-card {
    border-radius: 6px;
    transition: all 0.3s;
    position: relative;
    overflow: hidden;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }

    .order-header {
      display: flex;
      justify-content: space-between;
      margin-bottom: 15px;
      padding-bottom: 10px;
      border-bottom: 1px solid #f0f0f0;

      .order-no {
        font-weight: bold;
        color: #333;
      }

      .order-time {
        color: #666;
      }
    }

    .product-cell {
      display: flex;
      align-items: center;

      .product-image {
        width: 40px;
        height: 40px;
        margin-right: 10px;
        border-radius: 4px;
      }

      .product-name {
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }

    .order-info-section {
      margin-top: 15px;
      padding: 10px 0;
      border-top: 1px solid #f0f0f0;
    }

    .order-address {
      margin: 5px 0;
      color: #666;
      line-height: 1.6;
    }

    .order-actions {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 15px;
      padding-top: 10px;
      border-top: 1px solid #f0f0f0;
    }

    .order-footer {
      display: flex;
      justify-content: flex-end;
      margin-top: 10px;

      .order-total {
        font-weight: bold;

        .total-amount {
          color: #f56c6c;
          font-size: 18px;
        }
      }
    }
  }
}

// 状态标签样式增强
.el-tag {
  font-weight: bold;
  padding: 0 10px;
  height: 28px;
  line-height: 28px;

  &--success {
    background-color: rgba(103, 194, 58, 0.1);
    border-color: rgba(103, 194, 58, 0.2);
  }

  &--warning {
    background-color: rgba(230, 162, 60, 0.1);
    border-color: rgba(230, 162, 60, 0.2);
  }

  &--danger {
    background-color: rgba(245, 108, 108, 0.1);
    border-color: rgba(245, 108, 108, 0.2);
  }

  &--info {
    background-color: rgba(144, 147, 153, 0.1);
    border-color: rgba(144, 147, 153, 0.2);
  }
}
</style>
